package tool

import (
	"bufio"
	"fmt"
	"io"
	"log"
	"os"
	"os/exec"
)

func Exec_shell(s_cmd string) (string, bool) {
	cmd := exec.Command("/bin/bash", "-c", s_cmd)
	stdout, err := cmd.StdoutPipe()
	if err != nil {
		//log.Error("cmd StdoutPipe error:", err)
		return "", false
	}
	cmd.Start()

	var end_line string
	reader := bufio.NewReader(stdout)
	for {
		line, err2 := reader.ReadString('\n')
		if err2 != nil || io.EOF == err2 {
			break
		}
		end_line = line
	}

	fmt.Println(cmd.Process.Pid)
	return end_line, true
}
func PipeCommands(commands ...*exec.Cmd) ([]byte, error) {
	for i, command := range commands[:len(commands)-1] {
		out, err := command.StdoutPipe()
		if err != nil {
			return nil, err
		}
		command.Start()
		commands[i+1].Stdin = out
	}
	final, err := commands[len(commands)-1].Output()
	if err != nil {
		return nil, err
	}
	return final, nil
}

func RunInLinux(cmd string) string {
	log.Println("Running Linux cmd :", cmd)
	result, err := exec.Command("/bin/sh", "-c", cmd).Output()
	if err != nil {
		log.Println(err.Error())
	}
	return string(result)
}

func WriterFile(FilePath string, txt string) error {

	file, err := os.OpenFile(FilePath, os.O_WRONLY|os.O_CREATE, 06666)
	if err != nil {
		fmt.Println("打开文件错误= &v \n", err)
		return err
	}
	defer file.Close()
	//写入内容
	writer := bufio.NewWriter(file)
	writer.WriteString(txt)
	writer.Flush()
	return nil
}
